<?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Description: 评论
 *
 * @author      Eden
 * @datetime    2016/12/18 22:20
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

class Comment_Model extends API_Model
{

    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 主程序
     * @param array $params
     */
    public function run($params = array())
    {

        $params = array(
            'goodsId' => 5,
            'userId' => 2,
            'content' => '商品很不很,宝贝保存得非常好, 很满意的一次购物',
            'goodsStars' => 5,
            'expressStars' => 4
        );

        $send['state'] = false;
        do {

            if (!$this->checkParams($params)) {
                $send['error'] = $this->getError();
                break;
            }

            $this->load->helper('security');
            $content = strip_image_tags($params['content']);
            $content = encode_php_tags($content);

            $data = array(
                'goodsId' => $params['goodsId'],
                'userId' => $params['userId'],
                'content' => $content,
                'expressStars' => value($params, 'expressStars', 5),
                'goodsStars' => value($params, 'goodsStars', 5),
                'created' => dateTime(),
                'status' => 1
            );

            $this->db->insert('base_goods_comments', $data);
            if ($insertId = $this->db->insert_id()) {
                $send['state'] = true;
                $send['data'] =[
                    'commentId' => intval($insertId),
                    'goodsId' => intval($data['goodsId']),
                    'content' => $content,
                    'goodsStars' => intval($data['goodsStars']),
                    'expressStars' => intval($data['expressStars']),
                    'created' => formateTimeStamp($data['created'])
                ];
            } else {
                $send['error'] = '评论失败';
            }

        } while(false);
        $this->output->send($send);
    }

    /**
     * 检查参数
     * @param array $params
     * @return bool
     */
    private function checkParams(&$params = array())
    {
        if ($this->input->method(true) !== 'POST') {
            //$this->setError('非法请求');
            //return false;
        }

        if (empty($params['userId']) || empty($params['content']) || empty($params['goodsId'])) {
            $this->setError('参数错误');
            return false;
        }

        $params['expressStars'] = empty($params['expressStars']) || intval($params['expressStars']) < 0 ? 5 : intval($params['expressStars']);
        $params['goodsStars'] = empty($params['goodsStars']) || intval($params['goodsStars']) < 0 ? 5 : intval($params['goodsStars']);

        return true;
    }
}
